#include "StdAfx.h"

WdlCreator* Singleton<WdlCreator>::m_instance = 0;

ui32 GetChunkW(CMpqFile& f)
{
	ui32 sig;
	f.ReadInc(4, &sig);
	return sig;
}

void SkipChunkW(CMpqFile& f)
{
	ui32 size;
	f.ReadInc(4, &size);
	f.ModInc(size);
}

void WdlCreator::CreateWdl(std::string szMapName)
{
	std::string szFilePath = "World\\Maps\\";
	szFilePath += szMapName;
	szFilePath += "\\";
	szFilePath += szMapName;
	szFilePath += ".wdl";
	CMpqFile wdlFile(szFilePath);
	if(!wdlFile.IsOpened())
		return;
	FileBuffer tmpBuffer(wdlFile);
	ui32 signature = 0;
	while(signature = GetChunkW(wdlFile) != 'MAOF')
	{
		SkipChunkW(wdlFile);
	}
	wdlFile.ModInc(4);
	ui32 offsets[64][64];
	wdlFile.ReadInc(64 * 64 * 4, offsets);
	for(ui32 i = 0; i < 64; ++i)
	{
		for(ui32 j = 0; j < 64; ++j)
		{
			if(!offsets[i][j])
				continue;
			float coordX = j * TILESIZE;
			float coordZ = i * TILESIZE;
			for(ui32 k = 0; k < 17; ++k)
			{
				for(ui32 l = 0; l < 17; ++l)
				{
					float cCoordX = coordX + (l / 17.0f * TILESIZE);
					float cCoordZ = coordZ + (k / 17.0f * TILESIZE);
					float height = sD3D.GetLandHeight(cCoordX, cCoordZ);
					if(height > 65535.0f)
						continue;
					short sHeight = short(height + 0.5f);
					tmpBuffer.Write(offsets[i][j] + 0x8 + ((k * 17 + l) * 2), 2, &sHeight);
				}
			}
			for(ui32 k = 0; k < 16; ++k)
			{
				for(ui32 l = 0; l < 16; ++l)
				{
					float cCoordX = coordX + ((l + 0.5f) / 17.0f * TILESIZE);
					float cCoordZ = coordZ + ((k + 0.5f) / 17.0f * TILESIZE);
					float height = sD3D.GetLandHeight(cCoordX, cCoordZ);
					if(height > 65535.0f)
						continue;
					short sHeight = short(height + 0.5f);
					tmpBuffer.Write(offsets[i][j] + 0x8 + (17 * 17 * 2) + ((k * 16 + l) * 2), 2, &sHeight);
				}
			}
		}
	}
	std::string saveName = szMapName;
	saveName += ".wdl";
	char curDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, curDir);
	CreateDirectory("Save", 0);
	SetCurrentDirectory("./Save");
	CreateDirectory("World", 0);
	SetCurrentDirectory("./World");
	CreateDirectory("Maps", 0);
	SetCurrentDirectory("./Maps");
	CreateDirectory(szMapName.c_str(), 0);
	std::string nD = "./";
	nD += szMapName;
	SetCurrentDirectory(nD.c_str());
	tmpBuffer.SaveToFile(saveName);
	SetCurrentDirectory(curDir);
}